#include <QtGui>
#include <cmath>

#include "svplot.h"
#include "constants.h"

SvPlot::SvPlot(QWidget *parent)
    : QWidget(parent)
{
  m_x = 0;
  m_y = 0;
  m_relSatX = 0;
  m_relSatY = 0;
  resize(parent->width(), parent->height());
}

void SvPlot::changePos(double x,double y, double xRel, double yRel)
{
  if(m_x!=0)
  {
    m_xOld.push_back(m_x);
    m_yOld.push_back(m_y);
  }
  if(yRel!=0)
  {
    m_relSatX =xRel;
    m_relSatY =yRel;
    m_relSatTraceX.push_back(xRel);
    m_relSatTraceY.push_back(yRel);
  }
  m_y = y;
  m_x = x;
  repaint();
}
void SvPlot::paintEvent(QPaintEvent * /* event */)
{
    QPainter m_painter(this);
    m_painter.setRenderHint(QPainter::Antialiasing, true);
    m_side = qMin(width(), height());
    m_painter.setViewport((width() - m_side) , (height() - m_side) , m_side - 5, m_side - 5);
    m_centerX = m_painter.viewport().center().rx();
    m_centerY = m_painter.viewport().center().ry();
    double m_maxRadius = qMax(qMax(sqrt((m_x+m_relSatX)*(m_x+m_relSatX)+(m_y+m_relSatY)*(m_y+m_relSatY)),sqrt(m_x*m_x+m_y*m_y)),C_EARTH_RADIUS);
    m_tick = m_side/(2*m_maxRadius);
    if((m_x!=0)&&(m_y!=0))
        draw(&m_painter);
}

void SvPlot::draw(QPainter* m_painter)
{ 
  double radius = sqrt((m_x - m_centerX)*(m_x - m_centerX)+(m_y - m_centerY)*(m_y - m_centerY));
  m_painter->setBrush(Qt::blue);
  m_painter->drawEllipse(m_centerX - C_EARTH_RADIUS*m_tick,m_centerY - C_EARTH_RADIUS*m_tick,2*C_EARTH_RADIUS*m_tick,2*C_EARTH_RADIUS*m_tick);
  if(m_xOld.size()>1)
  {
    for(size_t i = 1;i < m_xOld.size(); i++)
    {
      m_painter->setBrush(Qt::black);
      m_painter->drawLine(m_xOld[i-1]*m_tick+m_centerX, m_yOld[i-1]*m_tick+m_centerY,m_xOld[i]*m_tick+m_centerX, m_yOld[i]*m_tick+m_centerY); 
      if(m_relSatTraceX.size()>1)
        m_painter->drawLine((m_xOld[i-1]-m_relSatTraceX[i-1])*m_tick+m_centerX, (m_yOld[i-1]-m_relSatTraceX[i-1])*m_tick+m_centerY,
                            (m_xOld[i]-m_relSatTraceX[i])*m_tick+m_centerX, (m_yOld[i]-m_relSatTraceX[i])*m_tick+m_centerY);
    }
  }
  m_painter->setBrush(Qt::red);
  m_painter->drawEllipse(m_x*m_tick+m_centerX, m_y*m_tick+m_centerY-5, 5, 5);
  if(m_relSatX!=0)
  {  
     m_painter->setBrush(Qt::yellow);  
     m_painter->drawEllipse((m_x-m_relSatX)*m_tick+m_centerX, (m_y-m_relSatY)*m_tick+m_centerY, 5, 5);
  }
    
}
